
#region Imported Namespaces
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Configuration;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.Design;
using System.Web.UI.WebControls;

using Constants = PHSRAG.Insight21.InsightUtilities.Constants;
using Helper = PHSRAG.WebControls.Helper;
using Policy = PHSRAG.Insight21.Policy;
using Utility = PHSRAG.Utility;
using UserContext = PHSRAG.Insight21.Context.UserContext;
using SC = PHSRAG.Insight21.SearchContext.SearchContext;
using Enums = PHSRAG.Security.Enumerations;
using PHSRAG.Insight21.SearchContext;
#endregion

namespace PHSRAG.Insight21.InsightWebControls
{
	#region Class Header
	/// <summary>
	/// The Header displays three things: a logo, an information bar and a navigation bar.
	/// The information bar contains the following:
	/// A welcome message, name of the user, current date and time, log-out link, and help link.
	/// The navigation bar contains the following links:
	/// Home, Agreements, Humans, Personnel, Purchasing, Admin
	/// All the links are wired to URL specified in the web.config file associated with the application that subsumes
	/// this control.
	/// </summary>
	/// <remarks>
	/// All Insight 2.1 pages should included this control to show on top of the page. Popup pages are exempt.
	/// </remarks>
	/// <example>
	/// The following example shows how the page would use this control. The registration of the control can be done
	/// simply by dropping the control on the page in design mode.
	/// <code>
	/// <![CDATA[
	/// <%@ Register TagPrefix="cc1" Namespace="PHSRAG.Insight21.InsightWebControls" Assembly="PHSRAG.Insight21.InsightWebControls" %>
	/// ...
	/// <body>
	/// ...
	/// <cc1:Header id="header" runat="server" />
	/// ...
	/// </body>
	/// ]]>
	/// </code>
	/// </example>
	[ToolboxData("<{0}:Header runat=server />")]
	[Designer(typeof(HeaderDesigner), typeof(IDesigner))]
	public class Header : System.Web.UI.WebControls.WebControl, INamingContainer
	{
		#region Constants
		private const string ClientsScriptKey = "clientScripts_8FD78E31-73FC-4f9d-80B7-FBC4C56819A4";
		private const string InsightHelpPath = "/InsightRoboHelp/!SSL!/WebHelp/InsightHelp.htm#";
		private const string NavigateCommand = "Navigate";
		private string				popUpHostPage = "../Common/ControlHost.aspx";
		private string				fundNumberLookupControl = "../Common/CommonControls/FundNumberLookup.ascx";
		#endregion

		#region Instance Variables
		private	Policy.ICachePolicy	cachePolicy;
		private LinkButton			helpLink;
		private HyperLink			logoutLink;
        private HyperLink           supportLink;
        private LinkButton fundNumberLookupLink;
		private	Policy.ICachePolicy	pageCachePolicy;
		private LinkButton			systemInfoLink;
		private Label				user;
		private UserContext			userContext;
		#endregion

		#region Module Navigation
		private LinkButton	adminLink;
		private LinkButton	agreementsLink;
		private LinkButton  clinicalTrialsLink;
		private LinkButton	homeLink;
		private LinkButton	humansLink;
      private LinkButton animalsLink;
		private LinkButton	personnelLink;
		private LinkButton	purchasingLink;
		private LinkButton	coiLink;
		private LinkButton	reportingLink;
		#endregion

		#region Public Properties
		/// <summary>
		/// Get/Set the name of the user (displayed in the information bar).
		/// </summary>
		public string User
		{
			get { EnsureChildControls(); return user.Text; }
			set { EnsureChildControls(); user.Text = value; }
		}
		/// <summary>
		/// Set the current module.
		/// </summary>
		public string ModuleName 		
		{
			get
         {
            return (string)cachePolicy.GetCachedObject(SC.CurrentModuleKey);
         }
			set 
			{
				cachePolicy.Cache(SC.CurrentModuleKey, value);
			}
		}
		#endregion

		#region Events
		/// <summary>
		/// Event to be handled by containing page.
		/// </summary>
		public event CommandEventHandler Navigate 
		{
			add		{ Events.AddHandler(NavigateCommand, value); }
			remove	{ Events.RemoveHandler(NavigateCommand, value); }
		}
		#endregion

		#region Overrides
		/// <summary>
		/// Create all controls that will be on the Header. Notice that the creation is more than just instantiating
		/// the controls. It also involves in generating the underlying HTML so that the controls shows up per the need.
		/// </summary>
		protected override void CreateChildControls()
		{
			CreateControls(userContext);
			GenerateControlTree(userContext);
		}

		/// <summary>
		/// Handler for the event raised when the page is being initialized.
		/// Retrieve the cache policy and page cache policy in force.
		/// </summary>
		/// <param name="e">Argument associated with the event</param>
		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);
			if (!IsDesignMode)
			{
				cachePolicy = (Policy.ICachePolicy)Page.Session[Policy.Names.CachePolicyKey];
				pageCachePolicy = (Policy.ICachePolicy)Page.Session[Policy.Names.CachePolicyKey];
				userContext = (UserContext)cachePolicy.GetCachedObject(UserContext.CacheKey);
			}
		}

		/// <summary>
		/// Invoked when an event is raised by a child control.
		/// </summary>
		/// <param name="source">Reference to the child control that raised the event</param>
		/// <param name="e">Argument associated with the event</param>
		/// <returns>True if the event was handle by this method; false otherwise</returns>
		protected override bool OnBubbleEvent(object source, EventArgs e)
		{
			// Events raised only by link/image buttons are handled. The name of the button which raised the event is stored
			// in the session and the associated URL is navigated to. The name stored in the session is used during page
			// load to highlight the link which was last clicked.
			bool handled = false;
			if (e is CommandEventArgs)
			{
				string commandName = null, targetPage = null;
                LinkButton button = source as LinkButton;
				if (button != null)
				{
					commandName = button.CommandName;
					targetPage = button.CommandArgument;
				}

                ImageButton imgButton = source as ImageButton;
                if (imgButton != null)
				{
					commandName = imgButton.CommandName;
					targetPage = imgButton.CommandArgument;
				}

				if ((commandName != null) && (targetPage != null))
				{
					if (Utility.Settings.GetKeyValue("PurgeCacheOnModuleChange", true))
					{
						string oldModuleName = ModuleName;
						if (!String.IsNullOrEmpty(oldModuleName))
							cachePolicy.Purge(oldModuleName, UserContext.CacheKey, Policy.Names.CachePolicyKey, Policy.Names.PageCachePolicyKey);
					}

					CommandEventHandler handler = (CommandEventHandler)Events[NavigateCommand];
					try
					{
						if (handler != null)
							// if the page doesn't want to redirect, it can throw an exception to prevent redirection
							handler(this, new CommandEventArgs(commandName, null));
							ModuleName = commandName;

							//Whenever the header nav links are selected, the search level must be set to Summary level.
							CommonSearchContext searchContext = (CommonSearchContext)cachePolicy.GetCachedObject(CommonSearchContext.CacheKey);
							if (searchContext != null)
								searchContext.CurrentLevel = SearchCriteria.Level.Summary;

							Page.Response.Redirect(targetPage);
						}
						catch{}

					handled = true;
				}
			}
			return handled;
		}

		/// <summary>
		/// Disable view state and ensure that child controls are created.
		/// </summary>
		/// <param name="e">Argument associated with the event</param>
		protected override void OnLoad(EventArgs e)
		{
			EnableViewState = false;
			base.OnLoad(e);
			EnsureChildControls();

			if (Utility.Settings.GetKeyValue("HideBackButtonHistory", false) )
                Page.ClientScript.RegisterStartupScript(GetType(), "TestScript",  
					"<script>history.go(1);</script>");
		}

		/// <summary>
		/// Creates and registers the javascript necessary to launch the context-sensitive help.  
		/// 
		/// This is achieved by settings in the Web.Config -- We attempt to find a page-specific
		/// help file.  If this fails, we attempt to find a module-specific help file.  If this 
		/// fails, we maintain the help file link to the overview help file for the application.
		/// </summary>
		protected override void OnPreRender(EventArgs e)
		{
			if (!IsDesignMode)
			{
                if (!Page.ClientScript.IsClientScriptBlockRegistered(ClientsScriptKey))
				{
					string insightPage = Path.GetFileName(Page.Request.Url.ToString());
					string activeModule = this.ModuleName;
               string helpURL = ConfigurationManager.AppSettings["insight"];
                    
					// TODO: //help does not have JE Fin. Txn. page yet
			
					bool isDetailPage = 
						(pageCachePolicy.GetCachedObject(Constants.AgreementsConstants.AgreementDetailsKey) != null);

					if (activeModule != null)
                        helpURL = ConfigurationManager.AppSettings[String.Format("{0}/{1}", activeModule,
						isDetailPage ?
						String.Format("{0}.details", insightPage.ToLower()) :
						insightPage.ToLower())];
					if ((activeModule != null) && String.IsNullOrEmpty(helpURL))
                        helpURL = ConfigurationManager.AppSettings[activeModule.ToLower()];
					
					const string features = "scrollbars=yes,resizable=yes,status=yes";
					string appPath = Helper.GetApplicationPath(Page);
                    appPath = appPath.TrimEnd('/');
					string script = string.Format(
						"<script language=\"javascript\">\n" +
						"function ShowHelp()\n" +
						"{{\n" +
						"\twindow.open('{0}' + '{1}{2}', '', '{3}'); \n" +
						"\treturn false; \n" +
						"}}\n" +
						"</script>\n"
						,appPath
						,InsightHelpPath
						,helpURL
						,features);

                    Page.ClientScript.RegisterClientScriptBlock(GetType(), ClientsScriptKey, script);
				}
			}
			base.OnPreRender (e);
		}

		#endregion

		#region Private Properties
		/// <summary>
		/// Return true if the control is in design mode.
		/// </summary>
		private static bool IsDesignMode
		{
			get { return HttpContext.Current == null; }
		}
		#endregion

		#region Private Methods
		/// <summary>
		/// Create all controls in the Header. Module navigation links are only created if the logged-in user has access
		/// to the corresponsing module. The Home link, of course, will always be created.
		/// </summary>
		private void CreateControls(Context.UserContext userContext)
		{
			Controls.Clear();
			user = new Label();
			User = IsDesignMode ? "John Doe" : string.Format("{0} {1}", userContext.FirstName, userContext.LastName);

			int moduleRoleBitmask = IsDesignMode ? -1 : userContext.ModuleRoleBitmask;
			int moduleBitmask = IsDesignMode ? -1 : userContext.ModuleBitmask;
			bool isUserSysAdmin = IsDesignMode ? true : userContext.IsUserSysAdmin;

			if( IsDesignMode || isUserSysAdmin)
			{
				systemInfoLink = new LinkButton();
				systemInfoLink.CommandName = systemInfoLink.Text = "System Info.";
				systemInfoLink.CommandArgument = GetNavigationKeyValue("Header.SystemInfoURL", string.Empty);
				systemInfoLink.CausesValidation = false;
			}

			helpLink = new LinkButton();
//			helpLink.CommandName = helpLink.Text = "Help";
			helpLink.Text = "Help";
			helpLink.CausesValidation = false;

			helpLink.Attributes["onclick"] = "javascript:ShowHelp(); return false;";

			fundNumberLookupLink = new LinkButton();
			fundNumberLookupLink.CommandName = fundNumberLookupLink.Text = "Fund # Lookup";
			fundNumberLookupLink.CausesValidation = false;

			string features = string.Format("width={0},height={1},scrollbars=yes,resizable=yes,status=no",
				Utility.Settings.GetKeyValue("SearchPopupWindow.Width", 750),
				Utility.Settings.GetKeyValue("SearchPopupWindow.Height", 500));

			fundNumberLookupLink.Attributes["onclick"] = string.Format("window.open('{0}?Load={1}', '', '{2}');return false;",
				popUpHostPage, fundNumberLookupControl, features);

            logoutLink = new HyperLink();
            logoutLink.Text = "Log Out";
            logoutLink.NavigateUrl = VirtualPathUtility.ToAbsolute("~/Logout.aspx");

            supportLink = new HyperLink();
            supportLink.Text = "Help Desk";
            supportLink.NavigateUrl = "~/Common/HelpDesk.aspx";

            //if the user has the Admin Module, add the link button.
			if (IsDesignMode || (((moduleBitmask & (int)Security.Enumerations.ModuleBit.Admin) != 0)))
			{	
				adminLink = new LinkButton();
				adminLink.CommandName = adminLink.Text = Constants.Modules.Admin;
				adminLink.CausesValidation = false;

				// If the user is a SysAdmin, KeyGiver, or PI the landing page will be  
				// User Management (search users) because they can give out access to other users.  
				// Otherwise, they have access to the Admin module for Humans Management only and the appropriate
				// landing page is based on their module role bitmask.
				if (IsDesignMode || (userContext.IsKeyGiver || 
					((moduleRoleBitmask  & (int)Security.Enumerations.ModuleRoleBit.SystemAdministrator |
					(int)Security.Enumerations.ModuleRoleBit.PrincipalInvestigator) != 0)))
						adminLink.CommandArgument = GetNavigationKeyValue("Header.AdminURL", string.Empty);
				
				else if (IsDesignMode || ((moduleRoleBitmask & (int)Enums.ModuleRoleBit.FormsManager) != 0))
					adminLink.CommandArgument =
						Utility.Settings.GetKeyValue("SubNavigation.Admin.Humans.FormsManagementURL", "");
				else if (IsDesignMode || ((moduleRoleBitmask & (int)Enums.ModuleRoleBit.ListManager) != 0))
					adminLink.CommandArgument =
						Utility.Settings.GetKeyValue("SubNavigation.Admin.Humans.ListRequestURL", "");
				else 
					adminLink.CommandArgument = 
						Utility.Settings.GetKeyValue("SubNavigation.Admin.WorkFlowManagerURL", "");

			}

			if (IsDesignMode || ((moduleBitmask & (int)Security.Enumerations.ModuleBit.Agreements) != 0))
			{
				agreementsLink = new LinkButton();
				agreementsLink.CommandName = agreementsLink.Text = Constants.Modules.Agreements;
				agreementsLink.CommandArgument = GetNavigationKeyValue("Header.AgreementsURL", string.Empty);
				agreementsLink.CausesValidation = false;
			}

			homeLink = new LinkButton();
			homeLink.CommandName = homeLink.Text = Constants.Modules.Home;
			homeLink.CommandArgument = IsDesignMode ? string.Empty : Utility.Settings.GetKeyValue("Header.HomeURL", "");
			homeLink.CausesValidation = false;

			if (IsDesignMode || ((moduleBitmask & (int)Security.Enumerations.ModuleBit.Humans) != 0))
			{
				humansLink = new LinkButton();
				humansLink.CommandName = humansLink.Text = Constants.Modules.Humans;
				humansLink.CommandArgument = GetNavigationKeyValue("Header.HumansURL", string.Empty);
				humansLink.CausesValidation = false;
			}
            if (IsDesignMode || ((moduleBitmask & (int)Security.Enumerations.ModuleBit.Animals) != 0))
            {
                animalsLink = new LinkButton();
                animalsLink.CommandName = animalsLink.Text = Constants.Modules.Animals;
                animalsLink.CommandArgument = GetNavigationKeyValue("Header.HumansURL", string.Empty);
                animalsLink.CausesValidation = false;
            }

			if (IsDesignMode || ((moduleBitmask & (int)Security.Enumerations.ModuleBit.Personnel) != 0))
			{
				personnelLink = new LinkButton();
				personnelLink.CommandName = personnelLink.Text = Constants.Modules.Personnel;
				personnelLink.CommandArgument = GetNavigationKeyValue("Header.PersonnelURL", string.Empty);
				personnelLink.CausesValidation = false;
			}

			if (IsDesignMode || ((moduleBitmask & (int)Security.Enumerations.ModuleBit.Purchasing) != 0))
			{
				purchasingLink = new LinkButton();
				purchasingLink.CommandName = purchasingLink.Text = Constants.Modules.Purchasing;
				purchasingLink.CommandArgument = GetNavigationKeyValue("Header.PurchasingURL", string.Empty);
				purchasingLink.CausesValidation = false;
			}

			if (IsDesignMode || ((moduleBitmask & (int)Security.Enumerations.ModuleBit.ClinicalTrials) != 0))
			{
				clinicalTrialsLink = new LinkButton();
				clinicalTrialsLink.CommandName = clinicalTrialsLink.Text = Constants.Modules.ClinicalTrials;
				clinicalTrialsLink.CommandArgument = GetNavigationKeyValue("Header.ClinicalTrialsURL", string.Empty);
				clinicalTrialsLink.CausesValidation = false;
			}

			if (IsDesignMode || ((moduleBitmask & (int)Security.Enumerations.ModuleBit.COI) != 0))
			{
				coiLink = new LinkButton();
				coiLink.CommandName = coiLink.Text = Constants.Modules.COI;
				coiLink.CommandArgument = GetNavigationKeyValue("Header.CoIURL", string.Empty);
				coiLink.CausesValidation = false;
			}
			if (IsDesignMode || ((moduleBitmask & (int)Security.Enumerations.ModuleBit.Reporting) != 0))
			{
				reportingLink = new LinkButton();
				reportingLink.CommandName = reportingLink.Text = Constants.Modules.Reporting;
				reportingLink.CommandArgument = GetNavigationKeyValue("Header.ReportingUrl", string.Empty);
				reportingLink.CausesValidation = false;
			}

		}

		/// <summary>
		/// Create the Welcome banner which will consist of the following: A welcome message with the user name, the current
		/// time, the logout link, and the help link.
		/// </summary>
		/// <param name="row"></param>
		private void CreateWelcomeBanner(TableRow row)
		{
			row.CssClass = "HeaderWelcomeBanner";

			TableCell cell = new TableCell();
			row.Cells.Add(cell);
			cell.Controls.Add(new LiteralControl("&nbsp;"));

			cell = new TableCell();
			row.Cells.Add(cell);

			Table table = new Table();
			cell.Controls.Add(table);
			table.Width = Unit.Percentage(100);
			TableRow r = new TableRow();
			table.Rows.Add(r);

			cell = new TableCell();
			r.Cells.Add(cell);
			cell.Controls.Add(new LiteralControl("<nobr>&nbsp;Welcome,&nbsp;</nobr>"));
			cell.Controls.Add(user);
			cell.Width = Unit.Percentage(70);
			cell.Attributes["align"] = "left";

			cell = new TableCell();
			cell.Attributes["align"] = "right";
			r.Cells.Add(cell);

			table = new Table();
			table.Width = Unit.Percentage(100);
			cell.Controls.Add(table);
			r = new TableRow();
			table.Rows.Add(r);

			cell = new TableCell();
			r.Cells.Add(cell);
			cell.Width = Unit.Percentage(30);
			cell.Controls.Add(new LiteralControl(DateTime.Now.ToString()));
			
			cell = new TableCell();
			r.Cells.Add(cell);
			cell.Controls.Add(fundNumberLookupLink);

			cell = new TableCell();
			r.Cells.Add(cell);
			cell.Controls.Add(logoutLink);

			cell = new TableCell();
			r.Cells.Add(cell);
			cell.Controls.Add(helpLink);

			if (systemInfoLink != null)
			{
				cell = new TableCell();
				r.Cells.Add(cell);
				cell.Controls.Add(systemInfoLink);
			}

            cell = new TableCell();
            r.Cells.Add(cell);
            cell.Controls.Add(supportLink);

            cell = new TableCell();
			row.Cells.Add(cell);
		}

		/// <summary>
		/// Create the module link cells. Only those links which have been created (based on security) will be parsed.
		/// The currently selected module (defaults to Home) is shown with a different style.
		/// </summary>
		/// <param name="row">Parent row in which the navigation link cells are to be created </param>
		private void CreateModuleLinks(TableRow row)
		{
			row.CssClass = "HeaderModuleNavigation";

			TableCell cell = new TableCell();
			row.Cells.Add(cell);

			const string imageFile = "../Images/Row1_Start.gif";
			Image image = new Image();
			image.ImageUrl = imageFile;
			cell.Controls.Add(image);
			cell.CssClass = "HeaderModuleNavigationImageCell";
			if (!IsDesignMode)
				cell.Height = (new System.Drawing.Bitmap(Context.Server.MapPath(imageFile))).Height;

			cell = new TableCell();
			row.Cells.Add(cell);
			cell.Controls.Add(homeLink);

			if (agreementsLink != null)
			{
				cell = new TableCell();
				row.Cells.Add(cell);
				cell.Controls.Add(agreementsLink);
			}

			if (humansLink != null)
			{
				cell = new TableCell();
				row.Cells.Add(cell);
				cell.Controls.Add(humansLink);
			}
            if (animalsLink != null)
            {
                cell = new TableCell();
                row.Cells.Add(cell);
                cell.Controls.Add(animalsLink);
            }

			if (clinicalTrialsLink != null)
			{
				cell = new TableCell();
				row.Cells.Add(cell);
				cell.Controls.Add(clinicalTrialsLink);
			}

			if (personnelLink != null)
			{
				cell = new TableCell();
				row.Cells.Add(cell);
				cell.Controls.Add(personnelLink);
			}
			
			if (purchasingLink != null)
			{
				cell = new TableCell();
				row.Cells.Add(cell);
				cell.Controls.Add(purchasingLink);
			}
		
			if (coiLink != null)
			{
				cell = new TableCell();
				row.Cells.Add(cell);
				cell.Controls.Add(coiLink);
			}
			if (reportingLink != null)
			{
				cell = new TableCell();
				row.Cells.Add(cell);
				cell.Controls.Add(reportingLink);
			}
			if (adminLink != null)
			{
				cell = new TableCell();
				row.Cells.Add(cell);
				cell.Controls.Add(adminLink);
			}
			

			CreateSelectedLinkAdornments(row);

			// Set the column span for the Welcome cell in the welcome banner row to span all module link cells.

			TableRow welcomeBannerRow = ((Table)row.Parent).Rows[0];
			welcomeBannerRow.Cells[1].ColumnSpan = row.Cells.Count - 1;	// Skip the image cell.

			// An extra cell is created at the tail-end of the module link row so as to extend the background to the right
			// edge of the containing table. The column span of the this cell is set based on the cell count in the
			// welcome banner row.

			cell = new TableCell();
			row.Cells.Add(cell);
			cell.Controls.Add(new LiteralControl("&nbsp;"));
			cell.ColumnSpan = welcomeBannerRow.Cells.Count - 2;	// Skip spacer cell and the welcome cells.
		}

		/// <summary>
		/// The selected link cell is given a prefix and suffix image as adornments. In addition the background of the
		/// cell is of a different style.
		/// </summary>
		/// <param name="row">Module navigation row which contains the module link cells</param>
		private void CreateSelectedLinkAdornments(TableRow row)
		{
			LinkButton selectedLink = GetSelectedLink();

			foreach (TableCell cell in row.Cells)
			{
				if ((cell.Controls.Count == 1) && (cell.Controls[0] == selectedLink))
				{
					cell.CssClass = "ModuleNavigationSelected";

					TableCell adornmentCell = new TableCell();
					adornmentCell.CssClass = "ModuleNavigationSelectedAdornment";
					row.Cells.AddAt(row.Cells.GetCellIndex(cell), adornmentCell);

					const string prefixImage = "../Images/Row1_Left.gif";
					Image image = new Image();
					image.ImageUrl = prefixImage;
					if (!IsDesignMode)
						adornmentCell.Width = (new System.Drawing.Bitmap(Context.Server.MapPath(prefixImage))).Width;
					adornmentCell.Controls.Add(image);
					
					break;
				}
			}
		}

		/// <summary>
		/// Setup the control tree to reflect the actual (and exact) layout of the controls within the Header.
		/// The Header has the following table layout:
		/// Row 1 Column 1: Insight logo
		/// Row 1 Column 2: banner-link table, whose layout is as follows:
		///		Row 1 Column 1: Spacer
		///		Row 1 Column 2: Welcome message
		///		Row 1 Column 3: Current time
		///		Row 1 Column 4: Logout link
		///		Row 1 Column 5: Help link
		///		Row 2 Column 1: Spacer
		///		Row 2 Column 2..n: Module navigation links (number depends on the access associated with the user)
		///		Row 2 Column n + 1: spacer to fill the rest of the row with background color
		/// </summary>
		private void GenerateControlTree(UserContext userContext)
		{
			Table table = new Table();
			Controls.Add(table);
			table.CssClass = "Header";

			TableRow row = new TableRow();
			table.Rows.Add(row);

			TableCell logoCell = new TableCell();
			row.Cells.Add(logoCell);
			TableCell bannerCell = new TableCell();
			row.Cells.Add(bannerCell);
			bannerCell.Attributes["align"] = "left";

			const string logoFile = "../Images/insight_logo.gif";
			Image logo = new Image();
			logo.ImageUrl = logoFile;
			logoCell.Controls.Add(logo);
			if (!IsDesignMode)
			{
				System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(Context.Server.MapPath(logoFile));
				logoCell.Width = bitmap.Width;
				logoCell.Height = bitmap.Height;
				bannerCell.Height = logoCell.Height;
			}

			Table bannerLinkTable = new Table();
			bannerCell.Controls.Add(bannerLinkTable);
			bannerLinkTable.CssClass = "HeaderBannerLink";

			TableRow welcomeBannerRow = new TableRow();
			bannerLinkTable.Rows.Add(welcomeBannerRow);
			CreateWelcomeBanner(welcomeBannerRow);

			TableRow moduleLinkRow = new TableRow();
			bannerLinkTable.Rows.Add(moduleLinkRow);
			CreateModuleLinks(moduleLinkRow);
		}

		private static string GetNavigationKeyValue(string key, string defaultValue)
		{
			return IsDesignMode ? defaultValue : Utility.Settings.GetKeyValue(key, defaultValue);
		}

		/// <summary>
		/// Retrieve the name of the link that was last clicked on.
		/// </summary>
		/// <returns>Reference to the link button corresponding to the clicked link</returns>
		private LinkButton GetSelectedLink()
		{
			// Anytime a link is clicked on, the OnBubbleEvent handler stores the name of the link in the session. Retrieve
			// that name and return the corresponding link button reference.
		
			if (!IsDesignMode)
			{
				object o = cachePolicy.GetCachedObject(SC.CurrentModuleKey);
				if (o != null)
				{
					string commandName = (string)o;
					if (adminLink != null && commandName == adminLink.CommandName)
						return adminLink;
					if (agreementsLink != null && commandName == agreementsLink.CommandName)
						return agreementsLink;
					if (humansLink != null && commandName == humansLink.CommandName)
						return humansLink;
                    if (animalsLink != null && commandName == animalsLink.CommandName)
                        return animalsLink;
					if (personnelLink != null && commandName == personnelLink.CommandName)
						return personnelLink;
					if (purchasingLink != null && commandName == purchasingLink.CommandName)
						return purchasingLink;
					if (clinicalTrialsLink != null && commandName == clinicalTrialsLink.CommandName)
						return clinicalTrialsLink;
					if (coiLink != null && commandName == coiLink.CommandName)
						return coiLink;
					if (reportingLink != null && commandName == reportingLink.CommandName)
						return reportingLink;
				}
			}
			return homeLink;
		}
		#endregion

		#region Internal Methods
		/// <summary>
		/// This method is ONLY invoked by the associated designer to show the control contents at design time.
		/// </summary>
		internal void Design()
		{
			EnsureChildControls();
		}
		#endregion
	}
	#endregion

	#region Class HeaderDesigner
	/// <summary>
	/// Designer associated with the Header control.
	/// </summary>
	/// <remarks>
	/// This class cannot be used directly.
	/// </remarks>
	public class HeaderDesigner : ControlDesigner
	{
		#region Overrides
		/// <summary>
		/// Force the Header control to create its child controls for display at design time.
		/// </summary>
		/// <returns>HTML representation of the Header control</returns>
		public override string GetDesignTimeHtml()
		{
			((Header)Component).Design();
			return base.GetDesignTimeHtml();
		}
		#endregion
	}
	#endregion
}

// --- EOF ---
